/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lcw.demo.imagepicker.slice;

import com.lcw.demo.imagepicker.GlideLoader;
import com.lcw.demo.imagepicker.ResourceTable;
import com.lcw.library.imagepicker.ImagePicker;
import com.lcw.library.imagepicker.utils.ResUtil;
import com.lcw.library.imagepicker.utils.TConstant;
import com.lcw.library.imagepicker.utils.TextUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import java.util.ArrayList;

public class MainAbilitySlice extends AbilitySlice {
    private static Text mTextView;
    private static final int REQUEST_SELECT_IMAGES_CODE = 1001;
    public static ArrayList<String> mImagePaths;
    private static Context mContext;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer container = (ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_ability_main, null, false);
        mContext = getAbility();
        mTextView = (Text) container.findComponentById(ResourceTable.Id_tv_select_images);
        checkReadPermission();
        setUIContent(container);
        findComponentById(ResourceTable.Id_bt_select_images).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                ImagePicker.getInstance()
                        .setTitle(ResUtil.getString(mContext, ResourceTable.String_title))//Set Title
                        .showCamera(true)//Sets whether to display the photographing button.
                        .showImage(true)//Set whether to display images.
                        .showVideo(true)//Set whether to display videos.
                        .filterGif(false)//Specifies whether to filter GIF images.
                        .setMaxCount(9)//Sets the maximum number of images to be selected. The default value is 1.
                        .setSingleType(true)//The image and video cannot be selected at the same time.
                        .setImagePaths(mImagePaths)//Setting History Selection Records
                        .setImageLoader(new GlideLoader())//Setting up a Custom Picture Loader
                        .start(getAbility(), REQUEST_SELECT_IMAGES_CODE);//REQUEST_SELECT_IMAGES_CODE is the request code of Intent invoking.
            }
        });
    }

    /**
     * THis method is called to start an ability and the result is returned.
     *
     * @param requestCode To generate a request
     * @param resultCode To get the result
     * @param resultData Return data will be there through intent
     */
    public void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == TConstant.RESULT_OK) {
            mImagePaths = resultData.getStringArrayListParam(ImagePicker.EXTRA_SELECT_IMAGES);
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(ResUtil.getString(mContext, ResourceTable.String_path_of_selected_image));
            for (String imagePath : mImagePaths) {
                stringBuffer.append(imagePath).append("\n\n");
            }
            if (!TextUtils.isEmpty(stringBuffer.toString())) {
                mTextView.setText(stringBuffer.toString());
            }
        }
    }

    /**
     * This method is used to check permission
     */
    private void checkReadPermission() {
        if (verifySelfPermission(SystemPermission.READ_USER_STORAGE) == IBundleManager.PERMISSION_GRANTED) {
        } else {
            requestPermissionsFromUser(new String[]{SystemPermission.READ_USER_STORAGE}, 0);
        }
    }

    /**
     * This method is called after permissions are granted/denied
     *
     * @param requestCode To generate a request
     * @param permissions List of permissions to be taken from user
     * @param grantResults Permisison result get by the user
     */
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0 || grantResults == null || grantResults.length == 0) {
            return;
        }
        if (requestCode == 0) {
            if (grantResults[0] == IBundleManager.PERMISSION_DENIED) {
                terminateAbility();
            } else {
            }
        }
    }

    @Override
    protected void onStop() {
        clearParams();
        super.onStop();
    }

    /**
     * This method is used to clear static params
     */
    private void clearParams() {
        mTextView = null;
        mImagePaths = null;
        mContext = null;
    }
}